<template>
    <div class="hello">
        <div style="height: 80vh;border: 1px solid;padding: 10px;box-sizing: border-box;overflow-y: scroll" ref="content">
            <p v-for="(item,index) in datalist" :key="index" style="text-align: left">{{item}}</p>
        </div>
        <div style="height: 10vh;display: flex;flex-direction: row;justify-content: center;align-items: center">
            <input type="text" v-model="msg" @keyup.enter="send()" style="border: 1px solid">
            <button @click="send()" style="border: 1px solid;border-radius: 4px;background: #fff;padding: 2px 10px;margin-left: 10px">发送</button>
        </div>
        <div>
            123
        </div>
    </div>
</template>

<script>
export default {
    name: 'message',
    data(){
        return {
            socket: null,
            url: 'ws://39.106.71.133:9000',
            msg:'',
            userInfo:this.$util.userInfo,
            datalist:[]
        }
    },
    mounted(){
        this.checktoken()
//        this.$router.replace('/login')
//        this.init()
    },
    destroyed(){
        if(this.socket){
            this.socket.close()
        }
    },
    methods: {
        send(){
            if(!this.socket){
                console.log('连接失败')
                this.init_websocket()
                return
            }
            this.socket.send(this.msg)
            this.msg = ''
        },
        init(){
            window.onunload = () => {
                if(this.socket){
                    console.log('刷新')
                    this.socket.close()
                }
            }
            this.init_websocket()
        },
        init_websocket(){
            try {
                this.socket = new WebSocket(this.url);
            } catch (e) {
               return console.log("socket不支持",e)
            }
            this.socket.onopen = this.websocket_open;
            this.socket.onmessage = this.websocket_message;
            this.socket.onerror = this.websocket_error;
            this.socket.onclose = this.websocket_close;
        },
        websocket_open(res){
            console.log('open',res)
        },
        websocket_message(message){
            console.log('消息',message)
            this.datalist.push(message.data)
            this.$refs.content.scrollTop = this.$refs.content.scrollHeight + 50
        },
        websocket_error(err){
            this.socket.close()
        },
        websocket_close(res){
            console.log('关闭',res)
            this.socket = null;
        },
        checktoken(){
            this.$util.checktoken(this.userInfo.uid,this.userInfo.token)
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
</style>
